//包含n个action creator 异步action 同步action
import io from 'socket.io-client'
import {
    AUTH_SUCCESS,
    ERROR_MSG,
    RESET_USER,
    RECEIVE_USER,
    RECEIVE_USERLIST,
    RECEIVE_MSG_LIST,
    RECEIVE_MSG,
    MSG_READ
} from './action-types'
import {
    reqLogin,
    reqRegister,
    reqUpdateUser,
    reqUser,
    reqUserList,
    reqChatMsgList,
    reqReadMsg
} from '../api/index'

/*单例对象
1.创建对象之前:判断对象是否已经创建，只有当不存在时才去创建
2.创建对象之后：保存对象*/
function initIO(dispatch, userid) {
    //1.创建对象之前:判断对象是否已经创建，只有当不存在时才去创建
    if (!io.socket) {
        //连接服务器,得到与服务器的连接对象
        io.socket = io('ws://localhost:4000')//创建对象之后：保存对象
        //绑定监听接收消息
        io.socket.on('receiveMsg', function (chatMsg) {
            console.log('客户端接收服务器发送的消息', chatMsg)
            //只有当chatMsg与当前用户相关的消息，才去分发同步action保存消息
            if (userid === chatMsg.from || userid === chatMsg.to) {
                dispatch(receiveMsg(chatMsg, userid))
            }
        })
    }

}

//异步发送消息的action
export const sendMsg = ({ from, to, content }) => {
    return dispatch => {
        console.log('客户端向服务器发送消息', { from, to, content })

        //发消息
        io.socket.emit('sendMsg', { from, to, content })
    }
}

//读取消息的异步action
export const readMsg = (from, to) =>{
    return async dispatch => {
        const res = await reqReadMsg(from)
        const result = res.data
        if(result.code===0){
            const count = result.data
            dispatch(msgRead({count,from,to}))
        }
    }
}

//异步获取消息列表数据
async function getMsgList(dispatch,userid) {
    initIO(dispatch,userid)
    const res = await reqChatMsgList()
    const result = res.data
    if (result.code === 0) {
        const { users, chatMsgs } = result.data
        //分发同步action
        dispatch(receiveMsgList({ users, chatMsgs, userid }))
    }
}


//授权成功的同步action
const authSuccess = (user) => ({ type: AUTH_SUCCESS, data: user })
//错误提示信息的同步action
const errorMsg = (msg) => ({ type: ERROR_MSG, data: msg })
//接收用户的同步action
const receiveUser = (user) => ({ type: RECEIVE_USER, data: user })
//重置用户的同步action
export const resetUser = (msg) => ({ type: RESET_USER, data: msg })
//接收用户列表的同步action
export const receiveUserList = (userlist) => ({ type: RECEIVE_USERLIST, data: userlist })
//接收消息列表的同步action
export const receiveMsgList = ({ users, chatMsgs, userid }) => ({ type: RECEIVE_MSG_LIST, data: { users, chatMsgs, userid } })
//接收一个消息的同步action
export const receiveMsg = (chatMsg, userid) => ({ type: RECEIVE_MSG, data: {chatMsg, userid} })
//读取某个聊天消息的同步action
const msgRead = ({count, from, to}) =>({type:MSG_READ, data:{count, from, to}})

//注册异步action
export const register = (user) => {
    const { username, password, password2, type } = user
    //表单的前台验证
    if (!username) {
        return errorMsg('用户名不能为空')
    } else if (password !== password2) {
        return errorMsg('两次密码要一致')
    }
    //表单数据合法，返回一个发Ajax请求的异步action函数
    return async dispatch => {
        //发送注册的异步Ajax请求
        const res = await reqRegister({ username, password, type })
        const result = res.data
        if (result.code === 0) {//成功
            getMsgList(dispatch,result.data._id)
            //分发成功的action
            dispatch(authSuccess(result.data))
        } else {//失败
            dispatch(errorMsg(result.msg))
        }
    }
}

//登录异步action
export const login = (user) => {
    const { username, password } = user
    //表单的前台验证
    if (!username) {
        return errorMsg('用户名不能为空')
    } else if (!password) {
        return errorMsg('密码不能为空')
    }
    return async dispatch => {
        //发送登录的异步Ajax请求
        const res = await reqLogin(user)
        const result = res.data
        if (result.code === 0) {//成功
            getMsgList(dispatch,result.data._id)
            //分发成功的action
            dispatch(authSuccess(result.data))
        } else {//失败
            dispatch(errorMsg(result.msg))
        }
    }
}

//更新异步action
export const updateUser = (user) => {
    return async dispatch => {
        const response = await reqUpdateUser(user)
        const res = response.data
        if (res.code === 0) {//更新成功 data
            dispatch(receiveUser(res.data))
        } else {//更新失败 msg
            dispatch(resetUser(res.msg))
        }
    }
}

//获取用户异步action
export const getUser = () => {
    return async dispatch => {
        //执行异步Ajax请求
        const res = await reqUser()
        const result = res.data
        if (result.code === 0) {//成功获取
            getMsgList(dispatch,result.data._id)
            dispatch(receiveUser(result.data))
        } else {
            dispatch(resetUser(result.msg))
        }
    }
}

//获取用户列表的异步action
export const getUserList = (type) => {
    return async dispatch => {
        //执行异步Ajax请求
        const res = await reqUserList(type)
        const result = res.data
        //得到结果后分发同步action
        if (result.code === 0) {
            dispatch(receiveUserList(result.data))
        }
    }
}

